<template>
  <div class="basic-layout">
    <div :class="['nav-side', isCollapse ? 'fold' : 'unfold']">
      <!--系统logo-->
      <div class="logo">
        <img src="./../assets/logo.png">
        <span v-show="showName">GK物联网平台</span>
      </div>
      <el-scrollbar>
        <!--导航菜单-->
        <el-menu :default-active="activeMenu" background-color="#001529" text-color="#fff" router :collapse="isCollapse"
          class="nav-menu">
          <tree-menu :userMenu="userMenu" />
        </el-menu>
      </el-scrollbar>
    </div>
    <div :class="['content-right', isCollapse ? 'fold' : 'unfold']">
      <div class="nav-top">
        <div class="nav-left">
          <div class="menu-fold" @click="toggle"><i class="el-icon-s-fold" /></div>
          <div class="bread">
            <bread-crumb />
          </div>
        </div>
        <div class="user-info">
          <el-badge class="full-screen">
            <i class="el-icon-full-screen" @click="toggleFullscreen" />
          </el-badge>
          <el-dropdown>
            <span class="user-link">
              <img :src="userInfo.avatarUrl" />
              <!-- {{userInfo.username}} -->
              <!-- <i class="el-icon-arrow-down el-icon--right"></i> -->
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="showUserInfo">个人信息</el-dropdown-item>
                <el-dropdown-item @click="changePassword">修改密码</el-dropdown-item>
                <el-dropdown-item @click="handleLogout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
      <div class="wrapper">
        <router-view></router-view>
      </div>
    </div>
    <el-dialog title="用户信息" v-model="showModal" :close-on-click-modal="false" :show-close="false" center width="450px">
      <div class="user-info-center">
        <el-upload class="avatar-uploader user-info-head" :show-file-list="false" :http-request="uploadAvatar"
          :before-upload="beforeAvatarUpload">
          <img v-if="userInfo.avatarUrl" :src="userInfo.avatarUrl" class="user-info-avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </div>
      <el-form ref="dialogForm" :model="userInfo" label-width="100px" :rules="rules">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userInfo.username" disabled placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="userInfo.name" disabled placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="userInfo.sex" size="medium" style="width: 100%;" disabled clearable>
            <el-option label="男" value='0'></el-option>
            <el-option label="女" value='1'></el-option>
            <el-option label="保密" value='2'></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="电话" prop="phoneNumber">
          <el-input v-model="userInfo.phoneNumber" disabled placeholder="请输入电话" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userInfo.email" disabled placeholder="请输入邮箱" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确定</el-button>
          <el-button @click="handleClose">取消</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog title="密码修改" v-model="showUpdatePassword" :close-on-click-modal="false" :show-close="false" width="450px"
      center>
      <el-form ref="changePasswordForm" :model="updatePasswordForm" label-width="100px" :rules="updatePasswordrules">
        <el-row>
          <el-col :span="24">
            <el-form-item label="新密码" prop="password">
              <el-input type="password" prefix-icon="el-icon-view" v-model="updatePasswordForm.password"
                placeholder="请输入新密码" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="验证码" prop="checkCode">
              <el-input v-model="updatePasswordForm.checkCode" placeholder="请输入验证码"
                style="width: 65%; margin-right: 5%;" />
              <div class="login-code">
                <el-button type="primary" :disabled="disableBtn" class="btn-code" @click="getCheckCode">{{ emailBtnName
                  }}
                </el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleUpdatePasswordClose">关闭</el-button>
          <el-button type="primary" @click="handleSubmitUpdatePassword">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ElMessageBox, ElMessage } from 'element-plus'
import TreeMenu from './TreeMenu.vue'
import BreadCrumb from './BreadCrumb.vue'
import screenfull from 'screenfull'
import utils from "../utils/utils"
import axios from 'axios'
export default {
  name: 'Home',
  components: { TreeMenu, BreadCrumb },
  data() {
    return {
      isCollapse: false,
      showName: true,
      userInfo: {},
      //弹框显示对象
      showModal: false,
      //修改密码显示对象
      showUpdatePassword: false,
      //定义表单校验规则
      rules: {
        username: [
          {
            required: true,
            message: "请输入用户名称",
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "请输入密码",
            trigger: "blur",
          },
        ],
        name: [
          {
            required: true,
            message: "请输入姓名",
            trigger: "blur",
          },
        ],
        sex: [
          {
            required: true,
            message: "请选择性别",
            trigger: "blur",
          },
        ],
        tel: [
          {
            required: true,
            message: "请输入电话",
            trigger: "blur",
          },
          {
            pattern: /1[3-9]\d{9}/,
            message: "请输入正确的手机号格式",
            trigger: "blur",
          },
        ],
        email: [
          {
            required: true,
            message: "请输入用户邮箱",
            trigger: "blur"
          },
          {
            pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
            message: "请输入正确的用户邮箱",
            trigger: "blur",
          },
        ],
        hiredate: [
          {
            required: true,
            message: "请选择入职时间",
            trigger: "blur"
          },
        ],
        roleIds: [
          {
            required: true,
            message: "请选择角色",
            trigger: "blur",
          },
        ],
      },
      userMenu: [],
      activeMenu: location.hash.slice(1),
      //设备控制表单
      updatePasswordForm: {},
      //定义表单校验规则
      updatePasswordrules: {
        password: [
          {
            pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z\W]{6,18}$/,
            required: true,
            message: "请输入必须包含字母和数字，且在6-18位之间的密码",
            trigger: "blur",
          },
        ]
      },
      emailBtnName: '获取验证码',
      disableBtn: false,
      btnTime: 0,
      circulationTimer: '',
      upLoadProgress: ''
    }
  },
  mounted() {
    this.isMobileDevice();
    this.getUserInfo();
    this.getRouters();
  },
  methods: {
    toggle() {
      var that = this;
      that.isCollapse = !that.isCollapse;
      if (that.isCollapse) {
        that.showName = !that.showName;
      } else {
        setTimeout(function () {
          that.showName = !that.showName;
        }, 300);
      }
    },
    toggleFullscreen() {
      if (screenfull.isEnabled) {
        screenfull.toggle()
      }
    },
    //判断当前设备是否为移动端
    isMobileDevice() {
      const ua = navigator.userAgent.toLowerCase();
      const t1 = /android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(ua);
      const t2 = !ua.match("iphone") && navigator.maxTouchPoints > 1;
      this.isCollapse = t1 || t2;
    },
    //用户信息展示
    showUserInfo() {
      this.showModal = true;
    },
    //取消
    handleClose() {
      this.showModal = false;
    },
    //确定
    handleSubmit() {
      this.showModal = false;
    },
    // 表单重置
    handleReset(form) {
      this.$refs[form].resetFields();
    },
    //密码修改
    changePassword() {
      this.showUpdatePassword = true;
    },
    //密码修改提交
    async handleSubmitUpdatePassword() {
      const msg = await this.$api.setNewPassword(this.updatePasswordForm);
      ElMessage({
        type: 'success',
        message: msg,
      })
      this.showUpdatePassword = false;
      this.handleReset("changePasswordForm");
    },
    //退出登陆
    handleLogout() {
      ElMessageBox.confirm('确定注销并退出系统吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const msg = await this.$api.logout();
        this.$store.commit("saveUserInfo", '');
        this.$store.commit('savePermissions', '');
        this.$store.commit('saveToken', '');
        this.userInfo = {};
        this.$router.push('/login');
        ElMessage({
          type: 'success',
          message: msg,
        })
      }).catch(() => { });
    },
    async getUserInfo() {
      try {
        const { user, permissions } = await this.$api.getUserInfo();
        this.userInfo = user;
        this.$store.commit("saveUserInfo", this.userInfo);
        this.$store.commit('savePermissions', permissions);
      } catch (error) {
        console.error(error);
      }
    },
    async getRouters() {
      try {
        const { menus } = await this.$api.getRouters();
        this.userMenu = menus;
        if (menus.length == 0) {
          const msg = await this.$api.applyPermission();
          ElMessage({
            message: '当前账户无任何权限，请联系管理员开通',
            type: 'warning',
          })
        }
      } catch (error) {
        console.error(error);
      }
    },
    getCheckCode() {
      this.$refs.changePasswordForm.validate((valid) => {
        if (valid) {
          this.disableBtn = true;
          this.btnTime = 60;
          this.timerBtn();
          this.$api.getEmailCheckCode({ email: this.userInfo.email }).then((res) => {
            ElMessage({
              type: 'success',
              message: '验证码已发送至邮箱',
            })
          })


        } else {
          return false;
        }
      })
    },
    timerBtn() {
      //进入倒计时
      if (this.btnTime > 0) {
        this.btnTime--;
        this.emailBtnName = this.btnTime + '秒后重试';
        this.circulationTimer = setTimeout(this.timerBtn, 1000)
      } else {
        this.btnTime = 0;
        this.emailBtnName = '获取验证码';
        this.disableBtn = false;
        clearTimeout(this.circulationTimer);
      }
    },
    //修改密码弹窗关闭
    handleUpdatePasswordClose() {
      this.showUpdatePassword = false;
      this.handleReset("changePasswordForm");
    },
    // 上传头像格式校验，文件大小校验
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 <= 2;
      if (!isJPG) {
        ElMessage({ message: '上传头像图片只能是JPG格式', type: 'error' })
        return isJPG;
      }
      if (!isLt2M) {
        ElMessage({ message: '上传头像图片大小不能超过2MB', type: 'error' })
        return isLt2M;
      }
      return isJPG && isLt2M;
    },
    //上传头像
    async uploadAvatar(file) {
      let formDatas = new FormData();
      formDatas.append('file', file.file);
      const { avatarUrl } = await this.$api.uploadAvatar(formDatas);
      this.userInfo.avatarUrl = avatarUrl;
      this.$store.commit("saveUserInfo", this.userInfo);
      ElMessage({ message: '头像上传成功', type: 'success' })
    }
  }
}
</script>

<style lang="scss">
.basic-layout {
  position: relative;

  .nav-side {
    z-index: 5;
    position: fixed;
    width: 200px;
    height: 100vh;
    background-color: #001529;
    color: #fff;
    overflow: hidden;
    transition: width .5s;

    .logo {
      display: flex;
      align-items: center;
      font-size: 18px;
      height: 50px;

      img {
        margin: 0 16px;
        width: 32px;
        height: 32px;
      }
    }

    .nav-menu {
      height: calc(100vh - 50px);
      border-right: none;
    }

    //合并
    &.fold {
      width: 64px;
    }

    //展开
    &.unfold {
      width: 200px;
    }
  }

  .content-right {
    margin-left: 200px;

    //合并
    &.fold {
      margin-left: 64px;
    }

    //展开
    &.unfold {
      margin-left: 200px;
    }

    .nav-top {
      height: 50px;
      line-height: 50px;
      display: flex;
      justify-content: space-between;
      border-bottom: 1px solid #ddd;
      padding: 0 20px;

      .nav-left {
        display: flex;
        align-items: center;

        .menu-fold {
          margin-right: 15px;
          font-size: 18px;
        }
      }

      .user-info {
        .full-screen {
          line-height: 30px;
          margin-right: 10px;
        }

        .user-link {
          cursor: pointer;
          color: #409eff;
          margin-right: 0px;

          img {
            width: 36px;
            height: auto;
            margin-right: 5px;
            border-radius: 100%;
            vertical-align: middle;
          }
        }
      }
    }

    .wrapper {
      background: #eef0f3;
      padding: 20px;
      height: calc(100vh - 50px);

      .main-page {
        background: #fff;
        height: 100%;
      }
    }
  }
}

.login-code {
  width: 30%;
  float: right;

  .btn-code {
    float: right;
    width: 100%;
  }
}

.user-info-center {
  text-align: center;

  .user-info-head {
    margin-bottom: 20px;

    .user-info-avatar {
      border-radius: 50%;
      width: 120px;
      height: 120px;
      display: block;
    }
  }
}
</style>
